<template>
  <section class="widget-address">
    <div class="search">
      <el-input :id="sid" v-model="value" :disabled="disabled" :placeholder="placeholder" type="text"></el-input>
      <div :id="tid" class="tip" />
    </div>
    <div class="map">
      <el-amap :amap-manager="mapmanager" :vid="vid" :zoom="zoom" :plugin="plugin" :events="events">
        <el-amap-marker v-for="(marker, index) in markers" :key="index" :position="marker" />
      </el-amap>
      <div v-if="disabled" class="mask"></div>
    </div>
  </section>
</template>
<script>
import { AMapManager, lazyAMapApiLoaderInstance } from 'vue-amap'
import mixins from './../mixins'
import { randomString } from '@/utils'
export default {
  name: 'VAddress',
  mixins: [mixins],
  props: {
    option: {
      type: Object,
      default: {}
    }
  },
  data () {
    const self = this
    return {
      sid: randomString(6),
      tid: randomString(6),
      center: [],
      mapmanager: new AMapManager(),
      zoom: 17,
      plugin: [
        {
          // 鹰眼
          pName: 'OverView',
          events: {
            init (instance) {
            }
          }
        },
        {
          // 搜索
          pName: 'PlaceSearch',
          events: {
            init (instance) {
            }
          }
        }
      ],
      markers: [],
      events: {
        init: () => {
          lazyAMapApiLoaderInstance.load().then(() => {
            self.initSearch()
          })
        },
        click (e) {
          self.markers = []
          const { lng, lat } = e.lnglat
          self.lng = lng
          self.lat = lat

          self.center = [lng, lat]
          self.markers.push([lng, lat])
          const geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: 'all'
          })
          geocoder.getAddress([lng, lat], (status, result) => {
            if (status === 'complete' && result.info === 'OK') {
              if (result && result.regeocode) {
                self.value = result.regeocode.formattedAddress
                self.handleChange()
                self.$nextTick()
              }
            }
          })
        }
      },
    }
  },
  watch: {
    value: {
      handler () {

      },
      deep: true
    }
  },
  computed: {
    vid () {
      return randomString(8)
    }
  },
  methods: {
    initSearch () {
      const _this = this
      const map = this.mapmanager.getMap()
      AMapUI.loadUI(['misc/PoiPicker'], (PoiPicker) => {
        var poiPicker = new PoiPicker({
          input: _this.sid,
          placeSearchOptions: {
            map: map,
            pageSize: 10
          },
          suggestContainer: _this.tid,
          searchResultsContainer: _this.tid
        })
        _this.poiPicker = poiPicker
        poiPicker.on('poiPicked', (poiResult) => {
          const source = poiResult.source
          const poi = poiResult.item
          if (source !== 'search') {
            poiPicker.searchByKeyword(poi.name)
          } else {
            poiPicker.clearSearchResults()
            _this.markers = []
            const lng = poi.location.lng
            const lat = poi.location.lat
            const address = poi.cityname + poi.adname + poi.name
            _this.center = [lng, lat]
            _this.markers.push([lng, lat])
            _this.value = address
            _this.handleChange()
          }
        })
      })
    },

    getValue () {
      return this.value
    },

    setValue (v) {
      this.value = v
    },

    setCheck () {
      let { required, value } = this
      let error = false, error_message = ''
      if (value !== undefined && value !== null) {
        value = value + ''
      }
      if (required && !value) {
        error = true;
        error_message = '必填选项不能为空';
      }
      this.error_ = error
      this.error_message_ = error_message
      this.fieldCheck()
    },

    handleChange () {
      this.check()
      this.dispatch_event('filed-value-change', this.value)
    }
  }

}
</script>
<style lang="scss" scoped>
.widget-address {
  .search {
    position: relative;
    .tip {
      width: 100%;
      max-height: 260px;
      position: absolute;
      top: 36px;
      z-index: 9999;
      overflow-y: auto;
      background-color: #fff;
    }
  }
  .map {
    height: 300px;
    margin-top: 5px;
    border-radius: 5px;
    overflow: hidden;
    position: relative;
    > section {
      height: 100%;
    }
    .mask {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      z-index: 9;
    }
  }
}
</style>